// 状态存储 （持久化处理）
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCartStore = defineStore('cart', () => {
    const items = ref<Array<{ id: number; name: string; quantity: number }>>([])

    // 从 localStorage 初始化
    const initFromLocalStorage = () => {
        const saved = localStorage.getItem('cart')
        if (saved) {
            items.value = JSON.parse(saved)
        }
    }

    // 保存到 localStorage
    const saveToLocalStorage = () => {
        localStorage.setItem('cart', JSON.stringify(items.value))
    }

    const addItem = (item: { id: number; name: string }) => {
        const existing = items.value.find(i => i.id === item.id)
        if (existing) {
            existing.quantity++
        } else {
            items.value.push({ ...item, quantity: 1 })
        }
        saveToLocalStorage()
    }

    const removeItem = (id: number) => {
        items.value = items.value.filter(i => i.id !== id)
        saveToLocalStorage()
    }

    // 初始化
    initFromLocalStorage()

    return {
        items,
        addItem,
        removeItem
    }
})